<script setup>
import { showDialog } from 'vant';
import BtnCenter from "@/components/Pengyq/TopButtonCenter.vue";
import bottomBtn from "@/components/Pengyq/bottomBtn.vue";
import { onMounted, computed } from "vue";
import { addItemEvaluates, addShopEvaluates } from "@/server/api/shopApi";
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useUseStore } from "@/stores/user";
import { ItemShopStore } from "@/stores/ItemAnShop";
import { showSuccessToast, showFailToast } from "vant";
import { showConfirmDialog } from 'vant';
import { ToastFun } from "@/hook/toast";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const user = useUseStore();
const route = useRoute();
const router = useRouter();
const shopCommodityId = ref();
const shopOrderId = ref(null)
const score = ref(0)
const message = ref()

const itemScore = ref(0)
const itemEvaluate = ref()
const ItemShop = ItemShopStore();

const userId = user.userId

const itemScores = ref({})  // 存储每个商品的评分
const itemEvaluates = ref({}) // 存储每个商品的评价内容

const isCommentPopupVisible = ref(false)  // 控制弹窗显示
const currentItem = ref(null)           // 当前被评论的商品
const currentRating = ref(0)          // 当前评分
const commentContent = ref('')          // 评论内容
const originalShopOrderDetailCount = ref(null)

const isclick = ref(false);
const itemOrderDetail = ref(null)
const shopOrderDetail = ref(null)
const ConfirmIsShow = ref(false);


//评价按钮
const openCommentModal = (item) => {
  currentItem.value = item;
  currentRating.value = 0; // 重置评分
  commentContent.value = ''; // 重置评论内容
  isCommentPopupVisible.value = true;
}
//取消
const closeCommentModal = () => {
  isCommentPopupVisible.value = false;
}

//网店评价
const sub = () => {
  if (!currentRating.value || !commentContent.value) {
    showDialog({
      title: '提示',
      message: "请完善评论，打分",
    }).then(() => {
      // on close
    });
    return;
  }
  const dto = {
    userId: user.userId,
    evaluate: commentContent.value,
    shopId: itemOrderDetail.value.shopId,
    commodityId: currentItem.value.commodityId,
    score: currentRating.value,
    orderId: currentItem.value.orderId
  }
  addItemEvaluate(dto)
}

// 新增网店商品评论
const addItemEvaluate = async (dto) => {
  try {
    ToastFun("Loading", { duration: 1000 });
    const res = await addItemEvaluates(dto);
    if (res?.data?.code === 200) {
      ToastFun("success", { msg: t("me.order.success") });
      currentItem.value.isCommented = true;
      itemOrderDetail.value.shopOrderDetail = itemOrderDetail.value.shopOrderDetail.filter(
        item => item.commodityId !== currentItem.value.commodityId
      );
      closeCommentModal();
      if (itemOrderDetail.value.shopOrderDetail.length === 0) {
        ToastFun("show", { msg: t("item.details.AllProductReviews") });
        router.push({ path: '/ItemBuyer' });
      }
    } else {
      ToastFun("", { msg: res?.data?.message || t("me.order.fail") });
    }
  } catch (error) {
    ToastFun("", { msg: t("item.details.NetworkError") });
  } finally {
    ToastFun("close");
  }
};

//返回
const handleReturn = () => {
  if (itemOrderDetail.value.shopOrderDetail.length > 0) {
    // 如果还有未评价的商品，提示用户
    showConfirmDialog({
      title: '提示',
      message:
        '还有商品未评价，返回后不能再评论。是否确认返回？',
    })
      .then(() => {
        // on confirm
        // 跳转到指定路径

        router.push({ path: '/ItemBuyer' });
      })
      .catch(() => {
        // on cancel
      });
  }

}




const allOrders = ref([
  {
    img: "/images/Me/shoe.png",
    title:
      "The new Holy Shield Gundam is not assembled with a 1/100 Holy Shield Gundam",
    price: " 39,99",
  },
]);


// 新增实体店商品评论
const addShopEvaluate = async (userId,
  evaluate,
  commodityId,
  score,
  orderId) => {
  console.log(userId,
    evaluate,
    commodityId,
    score,
    orderId);
  const res = await addShopEvaluates(userId,
    evaluate,
    commodityId,
    score,
    orderId);
  console.log(res.data);
  if (res.data.code === 200) {
    router.push({
      path: `/ItemBuyer`,

    });

  }
};
// 点击Confirm
const back = () => {
  isclick.value = true;
  setTimeout(() => {
    router.back();
  }, 200);
}

// 提交评论
const submitComment = () => {
  if (ItemShop.IdtStatus == "item") {
    console.log("item");

    addItemEvaluate(
      user.userId,
      message.value,
      commodityId.value,
      value.value,
      route.params.orderId
    );


  } else {
    if (!message.value || !score.value) {
      showDialog({
        title: '提示',
        message: "请完善评论，打分",
      }).then(() => {
        // on close
      });
      return;
    }
    addShopEvaluate(user.userId, message.value, shopCommodityId.value, score.value, shopOrderId.value);
  }
}



const onClickLeft = () => {
  router.push({
    path: `/ItemBuyer`,
  });
}

const submit = (item) => {
  const score = Number(itemScores.value[item.commodityId]);
  const evaluate = itemEvaluates.value[item.commodityId];

  // 这里可以进行提交操作
  console.log(`商品ID: ${item.commodityId}, 评分: ${score}, 评论: ${evaluate}`);
  const dto = {
    userId: user.userId,
    evaluate: evaluate,
    shopId: itemOrderDetail.value.shopId,
    commodityId: item.commodityId,
    score: score,
    orderId: item.orderId
  }
  console.log(dto)
  addItemEvaluate(dto)
}

onMounted(() => {
  // const OrderDetail= JSON.parse(route.query.OrderDetail);
  // // commodityId.value = route.params.id;
  // console.log(OrderDetail);

  if (ItemShop.IdtStatus == "item") {
    itemOrderDetail.value = JSON.parse(route.query.OrderDetail);
    originalShopOrderDetailCount.value = itemOrderDetail.value.shopOrderDetail.length
    console.log(itemOrderDetail.value);
  } else {
    shopOrderDetail.value = JSON.parse(route.query.OrderDetail);
    shopCommodityId.value = shopOrderDetail.value.commodityId
    shopOrderId.value = shopOrderDetail.value.orderId
    console.log(shopOrderDetail.value);
  }

});

const hasCommented = computed(() => {
  return itemOrderDetail.value.shopOrderDetail.length < originalShopOrderDetailCount.value;
})

const formatSpecification = (spec) => {
  return spec.replace(/[{}"]/g, '').replace(/,/g, ', ').replace(/:/g, ': ');
}

</script>
<template>
  <!-- <btn-center :title="$t('me.order.feedback')" /> -->

  <van-nav-bar :title="$t('me.order.feedback')" left-text="返回" left-arrow @click-left="onClickLeft"
    safe-area-inset-top="true" />

  <main class="DelShipped">

    <div v-if="itemOrderDetail !== null">
      <div v-for="item in itemOrderDetail.shopOrderDetail" :key="item.commodityId" class="order-item">
        <div class="image-container">
          <img :src="item.avatarImg" alt="商品图片" class="item-image">
        </div>
        <div class="info-container">
          <div class="commodity-id">商品ID: {{ item.commodityId }}</div>
          <div class="commodity-id"> {{ item.commodityName }}</div>
          <div class="commodity-id"> {{ formatSpecification(item.commoditySpecification) }}</div>

          <button class="comment-button" @click="openCommentModal(item)">评价</button>
        </div>
      </div>


      <!-- 返回按钮 -->
      <div v-if="hasCommented" class="return-button-container">
        <button class="return-button" @click="handleReturn">返回</button>
      </div>

      <!-- 评论弹窗 -->
      <van-popup :show="isCommentPopupVisible" position="top">
        <div class="comment-modal">
          <h3>评价商品</h3>
          <div class="score-container">
            <van-rate v-model="currentRating" :size="24" color="#ffd21e" void-icon="star" void-color="#eee" />
          </div>
          <textarea v-model="commentContent" placeholder="写下您的评价..." rows="4"></textarea>
          <div class="modal-actions">
            <button @click="sub" class="submit-button">提交评价</button>
            <button @click="closeCommentModal" class="cancel-button">取消</button>
          </div>
        </div>
      </van-popup>

    </div>

    <!-- <div class="detail" v-if="itemOrderDetail !== null" v-for=" item in itemOrderDetail.shopOrderDetail">

      <div class="title">
        <div class="text">{{ item.commodityId }}</div>
        <div class="text">{{ $t("me.feedbackStar") }}</div>
        <div class="value">
          {{ value }}
        </div>
        <van-rate v-model="itemScores[item.commodityId]" :size="20" color="#ffd21e" void-icon="star"
          void-color="#eee" />

      </div>
      <div>
        <van-cell-group inset>
          <van-field v-model="itemEvaluates[item.commodityId]" rows="8" autosize type="textarea" maxlength="150"
            :placeholder="$t('me.textFeedback')" show-word-limit
            style="padding-top: 10rem; font-size: 18rem; color: #000" />
          <div class="login">
    <img src="/public/images/Home/cat2.png" alt="" width="30" />
  </div>
        </van-cell-group>
        <div @click="submit(item)" style="display: flex; justify-self: self-end; margin: 30rem;">
          <button> 评价</button>
        </div>
      </div>
    </div> -->



    <div class="detail" v-if="shopOrderDetail !== null">
      <div class="title">
        <div class="text">{{ $t("me.feedbackStar") }}</div>
        <div class="value">
          {{ value }}
        </div>
        <van-rate v-model="score" :size="20" color="#ffd21e" void-icon="star" void-color="#eee" />
      </div>

      <van-cell-group inset>
        <van-field v-model="message" rows="8" autosize type="textarea" maxlength="150"
          :placeholder="$t('me.textFeedback')" show-word-limit
          style="padding-top: 10rem; font-size: 18rem; color: #000" />
        <!-- <div class="login">
          <img src="/public/images/Home/cat2.png" alt="" width="30" />
        </div> -->
      </van-cell-group>

      <div class="bnt" @click="submitComment">
        <bottomBtn :title="$t('order.submit')"></bottomBtn>
      </div>

    </div>



  </main>

  <div class="msk" v-show="ConfirmIsShow">
    <div class="box">
      <div class="title">Evaluate success</div>
      <div class="comfirm" :class="{ addBgc: isclick }" @click="back()">
        {{ $t("order.pay") }}
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.msk {
  background-color: rgba(73, 73, 73, 0.404);
  position: fixed;
  z-index: 999;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;

  .box {
    position: absolute;
    background-color: rgb(255, 255, 255);
    border-radius: 16rem;
    top: calc((100vh - 120rem) / 2);
    left: calc((100vw - 250rem) / 2);
    width: 250rem;
    height: 140rem;

    .title {
      height: 90rem;
      width: 250rem;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 22rem;
      border-bottom: 1rem solid #ddd;
      color: rgb(100, 46, 142);
      text-align: center;
    }

    .comfirm {
      width: 100%;
      font-size: 18rem;
      color: rgb(153, 153, 153);
      height: 50rem;
      line-height: 50rem;
      text-align: center;
      border-radius: 0 0 16rem 16rem;
    }
  }
}

.addBgc {
  background-color: #ddd;
}

main {
  font-size: 14rem;
  background-color: #f5f5f5;
  height: 100vh;
  box-sizing: border-box;

  .detail {
    .title {
      padding: 10rem 0;
      font-size: 16rem;
      padding-left: 10rem;
      display: flex;

      .text {
        margin: 0rem 10rem;
      }

      .value {
        margin: 0 5rem;
        line-height: 24rem;
      }
    }

    padding-top: 10rem;

    :deep(.van-cell-group) {
      line-height: 25rem;
      position: relative;

      .login {
        padding-bottom: 10rem;
        width: 90%;
        position: absolute;
        top: 10rem;
        left: 10rem;
        border-bottom: 1rem solid #d2d2d2;
      }
    }
  }

  /* 样式 */
  .order-item {
    display: flex;
    padding: 15px;
    margin: 10rem;
    border: 1px solid #f0f0f0;
    border-radius: 8px;
    background-color: #fff;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    position: relative;
    /* 为按钮定位 */
  }

  .image-container {
    flex: 0 0 80px;
    margin-right: 15px;
  }

  .item-image {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 8px;
    border: 1px solid #ddd;
  }

  .info-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  .commodity-id {
    font-size: 14rem;
    font-weight: bold;
    color: #333;
    margin-bottom: 8px;
  }

  .comment-button {
    position: absolute;
    right: 15px;
    bottom: 15px;
    padding: 6px 12px;
    background-color: #8a2be2;
    /* 紫色 */
    color: #fff;
    font-size: 14px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    text-align: center;
    transition: background-color 0.3s ease;
  }

  .comment-button:hover {
    background-color: #6a1bbd;
    /* 更深的紫色 */
  }

  .comment-button:active {
    background-color: #5a0f9e;
  }

  .comment-modal {
    padding: 20px;
  }

  .score-container {
    margin-bottom: 15px;
  }

  .star {
    font-size: 24px;
    cursor: pointer;
    margin-right: 5px;
  }

  .star-filled {
    color: #ffc107;
    /* 金黄色 */
  }

  .star-empty {
    color: #ddd;
    /* 浅灰色 */
  }

  textarea {
    width: 100%;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
    resize: none;
  }

  .modal-actions {
    display: flex;
    justify-content: space-between;
    margin-top: 15px;
  }

  .submit-button {
    background-color: #8a2be2;
    color: #fff;
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }

  .cancel-button {
    background-color: #ddd;
    color: #333;
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }

  .return-button-container {
    position: fixed;
    // bottom: 20px;
    right: 20px;
    z-index: 1000;
  }

  .return-button {
    padding: 10px 20px;
    background-color: #8a2be2;
    color: #fff;
    font-size: 16px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  }

  .return-button:hover {
    background-color: #6a1bbd;
  }

  .return-button:active {
    background-color: #5a0f9e;
  }

}
</style>
